package com.routz.shiro_demo.user_password_sample.dao;

import com.routz.shiro_demo.user_password_sample.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Slf4j
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insertUser(User user) {
        jdbcTemplate.update("INSERT INTO USER (ID,NAME,PASSWORD,SALT) VALUES (?,?,?,?)", user.getId(), user.getName(), user.getPassword(), user.getSalt());
    }

    public User findUserByName(String name) {
        return jdbcTemplate.query(
                "SELECT ID, NAME, PASSWORD, SALT FROM user WHERE NAME = ?", new Object[] { name },
                (rs, rowNum) -> User.builder()
                        .id(rs.getString("ID"))
                        .name(rs.getString("NAME"))
                        .password(rs.getString("PASSWORD"))
                        .salt(rs.getString("SALT"))
                        .build()).get(0);
    }

    public List<User> listUsers() {
        List<User> userlist = jdbcTemplate.query("SELECT * FROM USER", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                return User.builder()
                        .id(rs.getString(1))
                        .name(rs.getString(2))
                        .password(rs.getString(3))
                        .salt(rs.getString(4))
                        .build();
            }
        });
        return userlist;
    }

    public User findUserByNameAndPassword(String name, String password) {
        return jdbcTemplate.query(
                "SELECT ID, NAME, PASSWORD, SALT FROM user WHERE NAME = ? AND PASSWORD = ?", new Object[] { name, password },
                (rs, rowNum) -> User.builder()
                        .id(rs.getString("ID"))
                        .name(rs.getString("NAME"))
                        .password(rs.getString("PASSWORD"))
                        .salt(rs.getString("SALT"))
                        .build()).get(0);
    }

    public void updateSalt(String password, String salt) {
        jdbcTemplate.update("UPDATE USER SET PASSWORD = ?, SALT = ?", password, salt);
    }
}
